<?php

namespace app\modules\admin\controllers;

use Yii;
use yii\web\Response;
use app\modules\admin\components\BaseAdminController;
use app\components\Api;
use app\components\Wechat;
use app\components\Loyalty;
use app\components\Log;
use yii\helpers\ArrayHelper;
use yii\data\ArrayDataProvider;
use yii\filters\AccessControl;

class WechatController extends BaseAdminController
{

    public function behaviors()
    {
        return [
//            'access' => [
//                'class' => AccessControl::className(),
//                'rules' => [
//                    [
//                        'allow' => true,
//                        'actions' => [],
//                        'roles' => ['@'],
//                    ],
//                ],
//            ],
        ];
    }

    // 图文消息列表
    public function actionIndex()
    {
        return $this->render('index');
    }

    // 图片素材
    public function actionSourceImg()
    {
        $items = null;
        $total_count = 0;
        if (Yii::$app->request->isPost) {
            $offset = Yii::$app->request->post('offset');
            $count = Yii::$app->request->post('count');
            if ($offset < 0 || $count > 20) {
                Yii::$app->session->setFlash('error', '输入数据有误');
            } else {
                $data = [
                    'type' => 'image',
                    'offset' => $offset,
                    'count' => $count,
                ];
                $re = Wechat::material_batch_get($data);
                if (isset($re['item'])) {
                    $items = $re['item'];
                    $total_count = $re['total_count'];
                    $item_count = $re['item_count'];
                }
                // $this->bp($items);
            }
        }
        return $this->render('source-img', [
            'items' => $items,
            'total_count' => $total_count,
        ]);
    }

    // 上传图片
    public function actionUploadImg()
    {
        if (Yii::$app->request->isPost) {
            $file_name = $_FILES['file']['name'];
            $file_tmp = $_FILES['file']['tmp_name'];
            $tmp = $file_tmp;
            
            // $upload_dir = dirname(dirname(__FILE__)) . '/runtime/uploads/';

            // if (!is_uploaded_file($file_tmp)) {
            //     Yii::$app->session->setFlash('error', '图片错误');
            //     return $this->render('source-img');
            // }

            // $tmp = $upload_dir . $file_name;
            // if (!move_uploaded_file($file_tmp, $tmp)) {
            //     Yii::$app->session->setFlash('error', '图片错误');
            //     return $this->render('source-img');
            // }

            $access_token = Wechat::config('access_token');
            $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=' . $access_token;

            $data = [
                'media' => new \CURLFile($tmp, $_FILES['file']['type'], $file_name),
            ];

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $result = curl_exec($ch);
            curl_close($ch);

            if (@curl_errno($result) == 0) {
                $re = json_decode($result, true);
                if (isset($re['errmsg'])) {
                    Yii::$app->session->setFlash('error', $re['errmsg']);
                } else {
                    Yii::$app->session->setFlash('success', '上传成功，图片地址为:  <a href="' . $re['url'] . '" target="_blank">' . $re['url'] . '</a>');
                }
            } else {
                Yii::$app->session->setFlash('error', '上传失败');
            }
            return $this->render('source-img');
        }
    }

    public function actionCreateMember()
    {
        $data = [
            'card' => [
                'card_type' => 'MEMBER_CARD',
                'member_card' => [
                    'background_pic_url' => 'https://mmbiz.qpic.cn/mmbiz_png/UzsLSJicrzHfCA319RTQy5gtUEwqyD9AjM1hx9sWiaMRRjcMqGexf4F8Ag8u6my0pPZottZIQdicOWTLibRaej7u3Q/0',
                    'base_info' => [
                        'logo_url' => 'https://mmbiz.qpic.cn/mmbiz_png/UzsLSJicrzHfCA319RTQy5gtUEwqyD9AjmiclqA9uzbaQOCJzIibhnbL9eBd6g0np6bLv2JS9KUA0ezDDkJPq7vLw/0', // 卡券的商户logo，建议像素为300*300 必填
                        'code_type' => 'CODE_TYPE_ONLY_QRCODE', // Code展示类型 必填 (显示二维码)
                        'brand_name' => 'JSELECT', // 商户名字,字数上限为12个汉字 必填
                        'title' => 'XGATE DEMO卡', // 卡券名，字数上限为9个汉字 必填
                        'color' => 'Color020', // 券颜色。按色彩规范标注填写Color010-Color100 必填
                        'notice' => '仅作测试卡使用,不做任何商业用途', // 卡券使用提醒，字数上限为16个汉字 必填
                        'description' => '仅作测试卡使用,不做任何商业用途', // 卡券使用说明，字数上限为1024个汉字 必填
                        'service_phone' => '028-12345678', // 客服电话
                        'sku' => [
                            'quantity' => 10000, // 卡券库存的数量 必填
                        ],
                        'date_info' => [
                            'type' => 'DATE_TYPE_PERMANENT', // 永久有效类型 必填
                        ],
                        'custom_url_name' => '我的资料',
                        'custom_url' => 'http://winshare.onthemooner.com/index.php/member-binding/member-profile?appid=wxeca2e361be1de14c',
                        'custom_url_sub_title' => '',
                        'promotion_url_name' => '会员卡详情',
                        'promotion_url' => 'http://winshare.onthemooner.com/index.php/member-binding/member-card-info?appid=wxeca2e361be1de14c',
                        'use_all_locations' => true, // 会员卡是否支持全部门店，填写后商户门店更新时会自动同步至卡券 选填
                        'get_limit' => 1, // 每人可领券的数量限制，建议会员卡每人限领一张 选填
                        // 'pay_info' => [ // 选填
                        //     'swipe_card' => [ // 选填
                        //         'is_swipe_card' => true, // 是否设置该会员卡支持拉出微信支付刷卡界面 选填
                        //         // 'is_pay_and_qrcode' => ($model->is_pay_and_qrcode == 1) ? false : true, // 是否设置该会员卡中部的按钮同时支持微信支付刷卡和会员卡二维码 选填
                        //     ],
                        // ],
                    ],
                    // 'advanced_info' => [],
                    'prerogative' => '仅作测试卡使用,不做任何商业用途', // 会员卡特权说明,限制1024汉字 必填
                    'supply_bonus' => false, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
                    'supply_balance' => false, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
                    'wx_activate' => true, // 设置激活方式为 一键激活
                    'wx_activate_after_submit' => true, // 设置为一键激活中的跳转激活 
                    'wx_activate_after_submit_url' => 'http://winshare.onthemooner.com/index.php/member-binding/new-member?appid=wxeca2e361be1de14c', // 设置用户跳转激活后的地址为
                    // 'bonus_rule' => [ // 选填
                    //     'cost_money_unit' => '1', // 消费金额,以分为单位
                    //     'increase_bonus' => '1', // 对应增加的积分
                    //     'max_increase_bonus' => '5', // 用户单次可获取的积分上限
                    //     'init_increase_bonus' => '10', // 初始设置积分
                    //     'cost_bonus_unit' => '1', // 每使用多少积分
                    //     'reduce_money' => '1', // 抵扣xx元，（这里以分为单位）
                    //     'least_money_to_use_bonus' => '1', // 抵扣条件，满xx元（这里以分为单位）可用
                    //     'max_reduce_bonus' => '10', // 抵扣条件，单笔最多使用xx积分
                    // ],
                ],
            ],
        ];
        
        $card = Wechat::card_create($data);
        var_dump($card);
        die;
    }

    public function actionUpdateMember()
    {
        $data = [
            // 'card_id' => "p2Rmrt3QSQbzKUNYXtE9zgmOysFM",
            'card_id' => "p2Rmrt5wFyrAG1yKcHQyLVAf5XMs",
//                'card_type' => 'MEMBER_CARD',
            'member_card' => [
                'base_info' => [
                    'logo_url' => 'http://imgqn.koudaitong.com/upload_files/2014/05/27/FmW_0u9x06aG47okc4tA_ppSOqGb.jpg', // 卡券的商户logo，建议像素为300*300 必填
                    'code_type' => 'CODE_TYPE_ONLY_QRCODE', // Code展示类型 必填 (显示二维码)
//                        'brand_name' => 'MOMO超市会员卡中心', // 商户名字,字数上限为12个汉字 必填
                    'title' => 'Jebsen测试会员卡', // 卡券名，字数上限为9个汉字 必填
                    'color' => 'Color020', // 券颜色。按色彩规范标注填写Color010-Color100 必填
                    'notice' => '仅作测试卡使用,不做任何商业用途', // 卡券使用提醒，字数上限为16个汉字 必填
                    'description' => 'momo会员卡 测试用户激活,领卡', // 卡券使用说明，字数上限为1024个汉字 必填
                    'service_phone' => 6803504, // 客服电话
//                        'sku' => [
//                            'quantity' => '33', // 卡券库存的数量 必填
//                        ],
                    'custom_url_name' => '我的资料',
                    'custom_url' => 'http://winshare.onthemooner.com/index.php/member-binding/member-profile?appid=wxeca2e361be1de14c',
                    'custom_url_sub_title' => '',
                    'promotion_url_name' => '会员卡权益',
                    'promotion_url' => 'http://winshare.onthemooner.com/index.php/member-binding/member-card-info?appid=wxeca2e361be1de14c',
                    'use_all_locations' => true, // 会员卡是否支持全部门店，填写后商户门店更新时会自动同步至卡券 选填
                    'pay_info' => [ // 选填
                        'swipe_card' => [ // 选填
                            'is_swipe_card' => true, // 是否设置该会员卡支持拉出微信支付刷卡界面 选填
                                // 'is_pay_and_qrcode' => ($model->is_pay_and_qrcode == 1) ? false : true, // 是否设置该会员卡中部的按钮同时支持微信支付刷卡和会员卡二维码 选填
                        ],
                    ],
                ],

                    // 'advanced_info' => [],
                'prerogative' => '会员卡特权说明:测试卡使用,仅作admin使用', // 会员卡特权说明,限制1024汉字 必填
                'supply_bonus' => true, // 显示积分，填写true或false，如填写true，积分相关字段均为必填,若设置为true则后续不可以被关闭
                'supply_balance' => false, // 若设置为true则后续不可以被关闭。该字段须开通储值功能后方可使用
                'wx_activate' => true, // 设置激活方式为 一键激活
                'wx_activate_after_submit' => true, // 设置为一键激活中的跳转激活
                'wx_activate_after_submit_url' => 'http://winshare.onthemooner.com/index.php/admin/wechat/activate', // 设置用户跳转激活后的地址为               
            ],
        ];
        echo "<pre/>";
        $card = Wechat::card_update($data);
        var_dump($card);
        die;
    }


    public function actionActivate()
    {
        $session = Yii::$app->session;
        $session->set('appid', 'wxeca2e361be1de14c');
        $card_id = Yii::$app->request->get('card_id');
        $openid = Yii::$app->request->get('openid');
        $activate_ticket = Yii::$app->request->get('activate_ticket');

        // 请求获取用户填写的资料
        $info = Wechat::card_temp_userinfo_get(['activate_ticket' => $activate_ticket]);
        echo "<pre/>";
        var_dump($info);
        die;
    }

    public function actionSendCard()
    {
        $data = [
            'action_name' => 'QR_CARD',
            'expire_seconds' => '',
            'action_info' => [
                'card' => [
                    'card_id' => 'p2Rmrt3QSQbzKUNYXtE9zgmOysFM',
                    // 'code'=> '026888888888',
                    'outer_str' => 'QR_CARD'
                ]
            ]
        ];
        $res = Wechat::card_qr_create($data);
        if ($res['errmsg'] == 'ok' && isset($res['show_qrcode_url'])) {
            $this->redirect($res['show_qrcode_url']);
        }
    }

    public function actionCardList()
    {
        // echo 23;die;
        $username = Yii::$app->user->identity->username;
        $appid = Yii::$app->session->get('appid');
        echo "<pre>";
        var_dump($username);
        die;
    }

    public function actionActivateform()
    {
        $data = [
            // 'card_id' => 'p2Rmrt3QSQbzKUNYXtE9zgmOysFM',
            // 'card_id' => 'p2Rmrt8P3nizaSt5GsU4pRD0gGU0',
            // 'card_id' => 'p2Rmrt5wFyrAG1yKcHQyLVAf5XMs',
            'card_id' => 'p2RmrtxRf3wCUHotR6ErE0_W3Qj0',
            'service_statement' => [
                'name' => '会员守则',
                'url' => 'www.baidu.com'
            ],
            'bind_old_card' => [
                'name' => '老会员绑定',
                'url' => 'http://winshare.onthemooner.com/index.php/member-binding/old-member-binding?appid=wxeca2e361be1de14c'
            ],
            'required_form' => [
                'can_modify' => false,
                'common_field_id_list' => [
                    'USER_FORM_INFO_FLAG_MOBILE',
                    'USER_FORM_INFO_FLAG_SEX',
                    'USER_FORM_INFO_FLAG_NAME',
                ],
            ],
            'optional_form' => [
                'can_modify' => false,
                'common_field_id_list' => [
                    'USER_FORM_INFO_FLAG_BIRTHDAY',
                    'USER_FORM_INFO_FLAG_EMAIL',
                ],
                'custom_field_list' => []
            ]
        ];
        $res = Wechat::card_activate_form($data);
        echo "<pre>";
        var_dump($res);
        die;
    }

    public function actionQrcode()
    {
        return $this->render('qrcode');
    }

    public function actionBuildCard()
    {
        // 80011201-80011290
        // 80011801-80012010
        // 80011601-80011800
        $start = 80011601;
        $end = 80011800;
        for ($i = $start; $i <= $end; $i++) { 
            echo $i;
            echo '<br>';
        }
        exit;
    }

    public function actionDelCard()
    {
        $this->bp(Wechat::card_delete(['card_id' => 'p2Rmrt-hobOfu3wLA7o9eTYuRWFE']));
    }

}
